#! /usr/bin/python
# -*- coding: utf-8 -*-

import datetime

#some configuration value
maxUserDataUpdateIntervalHours = 24

from google.appengine.ext import db
import restutil
import logging

class XnUser(db.Model):
    xnuid = db.IntegerProperty()
    name = db.StringProperty(multiline=False)
    tinyurl_with_logo = db.StringProperty(multiline=False)
    headurl_with_logo = db.StringProperty(multiline=False)
    mainurl_with_logo = db.StringProperty(multiline=False)
    updateTime = db.DateTimeProperty(auto_now=True)

#Return the XnUser DB Model
def getXnUserById(xnuid):
    q = db.GqlQuery("SELECT * FROM XnUser WHERE xnuid = :xnuid", xnuid=xnuid)
    xnUserModel = q.get()
    return xnUserModel

#Return a List of XnUser DB Models
def getXnUserByIds(xnuidList):
    xnUserModelList = []
    xnuidNum = len(xnuidList)
    if xnuidNum > 0:
        q = db.GqlQuery("SELECT * FROM XnUser WHERE xnuid IN :xnuidList", xnuidList = xnuidList)
        xnUserModelList = q.fetch(xnuidNum, 0)
    return xnUserModelList

#update or create
def saveXnUser(xnUserModel):
    xnUserModel.put()

def getAndUpdateUserData(xnuid, sessionKey=None):
    xnUserModel = getXnUserById(xnuid)
    newXnUser = False
    if not xnUserModel:
        logging.debug('new UserModel for userid=' + str(xnuid))
        #print 'new UserModel for userid=' + str(xnuid)
        newXnUser = True
        xnUserModel = XnUser()
        xnUserModel.xnuid = xnuid
    else:
        logging.debug('old UserModel for userid=' + str(xnuid))
        #print 'old UserModel for userid=' + str(xnuid)
    nowTime = datetime.datetime.today()
    maxDelta = datetime.timedelta(hours=maxUserDataUpdateIntervalHours)
    if (newXnUser or nowTime - xnUserModel.updateTime > maxDelta) and sessionKey:
        restClient = restutil.rest(sessionKey)
        #tinyurlField = 'tinyurl_with_logo'
        #headurlField = 'headurl_with_logo'
        #mainurlField = 'mainurl_with_logo'
        tinyurlField = 'tinyurl'
        headurlField = 'headurl'
        mainurlField = 'mainurl'
        resultJson = restClient.usersGetInfo([xnuid], ['name',tinyurlField,headurlField,mainurlField])
        if (not resultJson['errCode']) and resultJson['resultData']:
            userData = resultJson['resultData'][0]
            name = userData.get('name')
            if name:
                xnUserModel.name = name
            tinyurl_with_logo = userData.get(tinyurlField)
            headurl_with_logo = userData.get(headurlField)
            mainurl_with_logo = userData.get(mainurlField)
            if tinyurl_with_logo and headurl_with_logo and mainurl_with_logo:
                xnUserModel.tinyurl_with_logo = tinyurl_with_logo
                xnUserModel.headurl_with_logo = headurl_with_logo
                xnUserModel.mainurl_with_logo = mainurl_with_logo
                logging.debug('Save a User Model for xnuid=' + str(xnuid))
                #print 'Save a User Model for xnuid=' + str(xnuid)
                saveXnUser(xnUserModel)
    return xnUserModel